package com.scalar.chiptrack.commons.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.AlarmUser;
import com.scalar.chiptrack.alarms.dao.AlarmDAO;
import com.scalar.chiptrack.commons.InternalComment;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.dao.InternalCommentsDAO;
import com.scalar.chiptrack.commons.forms.InternalCommentsForm;
import com.scalar.chiptrack.sales.SalesPerson;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * User: Sujan
 * Date: Mar 20, 2007
 * Time: 3:53:36 PM
 */
public class InternalCommentsAction extends ChipTrackAction
{

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session = request.getSession();
        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );
        if( user == null )
        {
            // Write XML to response.
            response.setContentType("application/xml");
            String commentsXML = "<commts><commt user=' ' ts=' '>Session has been time out, Your request could not be processed. Please login again</commt></commts>";
            response.getWriter().write( commentsXML );
            return null;
        }
        InternalCommentsForm internalCommentsForm = (InternalCommentsForm)form;
        String action = request.getParameter( "action" );
        if ( "getAllComments".equalsIgnoreCase( action ) )
        {

            ArrayList internalComments = InternalCommentsDAO.getAllComments( null, internalCommentsForm.getCommentsGroupId() );
            String commentsXML = getInternalCommentsXML(internalComments);
            // Write XML to response.
            response.setContentType("application/xml");
            response.getWriter().write( commentsXML );
        }
        if ( "insertComment".equalsIgnoreCase( action ) )
        {
            InternalComment internalComment = new InternalComment();
            internalComment.setComment( internalCommentsForm.getInternalComment() );
            internalComment.setCommentGroupId( internalCommentsForm.getCommentsGroupId() );
            internalComment.setEnteredById( user.getUserId() );
            InternalCommentsDAO.insertInternalComment( null, internalComment );

            notifiyInternalComments( internalCommentsForm.getCommentsGroupId(), internalComment, -1, null );

            ArrayList internalComments = InternalCommentsDAO.getAllComments( null, internalCommentsForm.getCommentsGroupId() );
            String commentsXML = getInternalCommentsXML(internalComments);
            response.setContentType("application/xml");
            response.getWriter().write( commentsXML );
        }
        return null;
    }
    private String getInternalCommentsXML ( ArrayList internalComments )
    {
        StringBuffer commentsXML = new StringBuffer();
        commentsXML.append ( "<commts>" );
        int liseSize = (internalComments == null ) ? 0 : internalComments.size();
        for ( int i=0; i < liseSize; i++ )
        {
            InternalComment internalComment =  ( InternalComment ) internalComments.get( i );
            commentsXML.append ( "<commt user='" ).append ( internalComment.getEnteredById() ).append ( "'");
            commentsXML.append ( " ts='" ).append ( internalComment.getTimeStamp() ).append ( "'>");
            commentsXML.append ( ResponseUtils.filter( internalComment.getComment() ) ).append ( "</commt>" );
        }
        commentsXML.append ( "</commts>" );
        return commentsXML.toString();
    }

    /**
     *
     * @param groupId
     * @param internalComment if null then all the internal comments will be notified<br>
     *  else only the given InternalComment is notified
     * @throws Exception
     */
    public static void notifiyInternalComments ( String groupId, InternalComment internalComment, int Id, Alarm alarm ) throws Exception
    {
        if ( groupId.startsWith("Quotation") )
        {
            if(ConfigManager.isSendQuotationInternalCommentsMail())
            {
                String quotationNo=groupId.substring(groupId.indexOf("-")+1);
                //int alarmId = QuotationDAO.getAlarmIdByQuotationNo( null, quotationNo );
                if( alarm != null && alarm.getId() > 0 )
                {
                    String message = prepareInternalCommentsMessage( groupId, internalComment );
                    if ( message != null )
                    {
                        //int quotationId = QuotationDAO.getQuotationIdByQuotationNo( null, quotationNo );

                        message += "<BR><a target='_new' href='http://" + ConfigManager.getChipTracHost() + "/" + ConfigManager.getChipTracContext();
                        message += "/quotationView.do?action=printQuotation&quotationId="+Id+"&quotationNo=" +quotationNo + "'>";
                        message += "<B>Please click here to view Quote page</B></a><BR>";

                        alarm.setSubject( "Quote Notification - Quote Number: " + quotationNo + " Internal Commnets added");
                        alarm.notifyAllRecipientsForInternalComments ( message );
                    }
                }
            }
        }
        else if ( groupId.startsWith("SalesOrder"))
        {                           
            if(ConfigManager.getBooleanProperty(ConfigManager.SEND_SO_INTERNAL_COMMENTS_MAIL) )
            {
                String soNo=groupId.substring(groupId.indexOf("-")+1);
                //int alarmId = NewSalesOrderDAO.getAlarmIdBySalesOrderNo( null, soNo );
                if( alarm != null && alarm.getId() > 0 )
                {
                    String message = prepareInternalCommentsMessage( groupId, internalComment );
                    if ( message != null )
                    {
                        //order.do?salesOrderId=1894&isSample=1
                        message += "<BR><a target='_new' href='http://" + ConfigManager.getChipTracHost() + "/" + ConfigManager.getChipTracContext();
                        message += "/order.do?salesOrderId="+Id+"&isSample=1'>";
                        message += "<B>Please click here to view SalesOrder page</B></a><BR>";

                        alarm.setSubject( "Sales Order Notification - SalesOrder Number: " + soNo + " Internal Commnets added");
                        alarm.notifyAllRecipientsForInternalComments ( message );
                    }
                }
            }
        }
    }
    private static String prepareInternalCommentsMessage( String groupId, InternalComment internalComment ) throws Exception
    {
        StringBuffer message = new StringBuffer();
        message.append ( "The Following Internal Comment is added <br>" );
        message.append ( "<table>" );
        message.append ( "<tr><td colspan=3 bgcolor='#993333' style='COLOR: #FFFFFF; font-family: arial; font-size: 10pt; font-weight:bold'>Comments</td>" );
        if ( internalComment != null )
        {
            message.append ( "<tr bgcolor='#DEE1E2'><td width='10%' valign='top' style='COLOR: #000000; font-family: verdana; font-size: 8pt; font-weight:bold'>" );
            message.append ( internalComment.getEnteredById() + ":" );
            message.append ( "</td>" );
            message.append ( "<td width='75%' valign='top' style='font-family: Arial, Helvetica, sans-serif; font-size: 13px;'>" );
            message.append ( internalComment.getComment() );
            message.append ( "</td>" );
            message.append ( "<td width='15%' valign='top' class='bodytext'>" );
            message.append ( internalComment.getTimeStamp() );
            message.append ( "</td>" );
            message.append ( "</tr>");
        }
        else
        {
            ArrayList internalComments = InternalCommentsDAO.getAllComments( null, groupId );
            if ( internalComments != null && internalComments.size() > 0 )
            {
                int size = internalComments.size();
                for ( int i=0; i < size; i++ )
                {
                    internalComment = (InternalComment) internalComments.get(i);
                    message.append ( "<tr bgcolor='" + (i%2==0 ? "#DEE1E2" : "#FFFFEE") + "'><td width='10%' valign='top' style='COLOR: #000000; font-family: verdana; font-size: 8pt; font-weight:bold'>" );
                    message.append ( internalComment.getEnteredById() + ":" );
                    message.append ( "</td>" );
                    message.append ( "<td width='75%' valign='top' style='font-family: Arial, Helvetica, sans-serif; font-size: 13px;'>" );
                    message.append ( internalComment.getComment() );
                    message.append ( "</td>" );
                    message.append ( "<td width='15%' valign='top' class='bodytext'>" );
                    message.append ( internalComment.getTimeStamp() );
                    message.append ( "</td>" );
                    message.append ( "</tr>");
                }
            }
            else
            {
                return null;
            }
        }
        message.append ( "</table>");
        return message.toString();
    }
}
